package com.atguigu.realtime.app.dwd.db;


import com.atguigu.realtime.app.BaseSqlApp;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.SQLUtil;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;


/**
 * com.atguigu.realtime.app.dwd.db.Dwd_13_DwdToolCouponPay
 * 工具域优惠券使用(支付)事务事实表
 *
 *  读取优惠券领用表数据，筛选优惠券支付数据，写入 Kafka 优惠券支付主题。
 *      用户使用优惠券支付时，优惠券领用表的 used_time 字段会更新为支付时间
 *       ① 操作类型为 update；
 *          ② 修改了 used_time 字段。
 */
public class Dwd_13_DwdToolCouponPay extends BaseSqlApp {
    public static void main(String[] args) {
        new Dwd_13_DwdToolCouponPay().init(
                3013,2,
                "Dwd_13_DwdToolCouponPay"
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env,
                          StreamTableEnvironment tEnv) {
        tEnv.getConfig().setIdleStateRetention(Duration.ofSeconds(10));

        // 1. 读取ods_db
        readOdsDb(tEnv, "Dwd_11_DwdToolCouponGet");


        // TODO 2. 读取优惠券领用表数据，筛选优惠券使用（支付）数据
        Table result = tEnv.sqlQuery("select\n" +
                "data['id'] id,\n" +
                "data['coupon_id'] coupon_id,\n" +
                "data['user_id'] user_id,\n" +
                "data['order_id'] order_id,\n" +
                "date_format(data['used_time'],'yyyy-MM-dd') date_id,\n" +
                "data['used_time'] used_time,\n" +
                "`old`,\n" +
                "ts\n" +
                "from ods_db\n" +
                "where `database`='gmall2022' \n" +
                "and `table` = 'coupon_use'\n" +
                "and `type` = 'update'\n" +
                "and data['used_time'] is not null");

        tEnv.createTemporaryView("coupon_use", result);


        tEnv.executeSql("create table dwd_tool_coupon_pay(\n" +
                "id string,\n" +
                "coupon_id string,\n" +
                "user_id string,\n" +
                "order_id string,\n" +
                "date_id string,\n" +
                "payment_time string,\n" +
                "ts bigint \n" +
                ")" + SQLUtil.getKafkaSink(Constant.TOPIC_DWD_TOOL_COUPON_PAY));

        result.executeInsert("dwd_tool_coupon_pay");
    }
}

/*

 */